package com.bluedot.www.core.utils;

import com.spire.doc.Document;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @author He Peng
 * @version 1.0
 * @date 2021/10/18 9:23
 */
public class WordUtil {
    /**特殊标志的正则表达式*/
    public static Pattern specialMark = Pattern.compile("\\$\\{.*?}");
    /**日志*/
    static Logger logger = LoggerFactory.getLogger(WordUtil.class);


    /**
     * 替换Word文件中 ${} 标识的特殊字符
     * <br>
     * <strong>注意：如果存在部分特殊表示无法替换，请尝试将 ${} 的整个字符串复制到word中，否者有可能不会识别为一个整体</strong>
     * @param doc: Sprire Document
     * @param map: 指定字符${} 与 需要替换的为字符串的对应关系
     * @author He Peng
     * @date 2021/10/18 8:30
     */
    public static void replaceSpecialWord(Document doc, Map<String, String> map) {
        TextSelection[] allPattern = doc.findAllPattern(specialMark);
        for (TextSelection textSelection : allPattern) {
            String tmp = map.get(textSelection.getSelectedText());
            if (tmp != null) {
                int res = doc.replace(textSelection.getSelectedText(), tmp, true, true);
                if (res == 0) {
                    logger.info("特殊标志：" + tmp + " 替换失败");
                }
            }
        }
    }


    /**
     * 指定匹配的正则表达式替换
     * @param doc: Spire Document
     * @param map: 映射关系
     * @param pattern: 正则表达式
     * @author He Peng
     * @date 2021/10/18 9:42
     */
    public static void replaceSpecialWord(Document doc, Map<String, String> map, Pattern pattern) {
        specialMark = pattern;
        replaceSpecialWord(doc, map);
    }


    /**
     * 替换Word文档中的同一占位符，为多张不同的图片，每一个占位符对应一张图片，
     * 如果占位符比图片数量多则该占位符会被写为空字符串
     * @param doc: Spire Document
     * @param matchString: 占位符
     * @param imgList: 图片输入流集合
     * @author He Peng
     * @date 2021/10/22 20:09
     */
    public static void replaceTextToImage(Document doc, String matchString, List<InputStream> imgList, float rate) {
        TextSelection[] selections = doc.findAllString(matchString, true, true);
        int total = imgList.size();
        int count = 0;
        for (TextSelection selection : selections) {
            if (count < total && imgList.get(count) != null) {
                DocPicture pic = new DocPicture(doc);
                pic.loadImage(imgList.get(count));
                zoomImage(pic, rate);
                TextRange range = selection.getAsOneRange();
                int index = range.getOwnerParagraph().getChildObjects().indexOf(range);
                range.getOwnerParagraph().getChildObjects().insert(index, pic);
                range.getOwnerParagraph().getChildObjects().remove(range);
                count++;
            } else {
                doc.replace(selection.getSelectedText(), "", true, true);
                break;
            }
        }
    }

    /**
     * 未设置缩放比例，则默认不缩放
     * @param doc: Spire Document
     * @param matchString: 占位符
     * @param imgList:  图片输入流集合
     * @author He Peng
     * @date 2021/10/23 9:38
     */
    public static void replaceTextToImage(Document doc, String matchString, List<InputStream> imgList) {
        replaceTextToImage(doc, matchString, imgList, 1);
    }


    /**
     * 按照横纵比缩放图片
     * @param pic: Spire 图片对象
     * @param rate: 缩放比例 0.1<= rate <=10，
     * @author He Peng
     * @date 2021/10/23 9:28
     */
    public static void zoomImage(DocPicture pic, float rate) {
        if (rate < 0.1 || rate > 10) {
            throw new IllegalArgumentException("缩放比例参数的数值范围为：0.1<= rate <=10，不能超过此范围");
        }
        float originalWidth = pic.getWidth();
        float originalHeight = pic.getHeight();
        pic.setWidth(originalWidth * rate);
        pic.setHeight(originalHeight * rate);
    }

}
